package com.cirkana.serial;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class SerializationUtil {

	public static final byte[] serialize(SerializablePassData data)
			throws SerializationException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		DataOutputStream dataOut = new DataOutputStream(byteOut);
		try {
			data.serialize(dataOut);
			return byteOut.toByteArray();
		} catch (SerializationException e) {
			throw e;
		} catch (Exception e) {
			throw new SerializationException(e);
		} finally {
			try {
				dataOut.close();
			} catch (IOException e) {
				throw new SerializationException(e);
			}
			try {
				byteOut.close();
			} catch (IOException e) {
				throw new SerializationException(e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static final SerializablePassData deserialize(byte[] bytes,
			Class type) throws SerializationException {
		ByteArrayInputStream byteIn = null;
		DataInputStream dataIn = null;
		try {
			SerializablePassData data = (SerializablePassData) type
					.newInstance();
			byteIn = new ByteArrayInputStream(bytes);
			dataIn = new DataInputStream(byteIn);
			data.deserialize(dataIn);
			return data;
		} catch (SerializationException e) {
			throw e;
		} catch (Exception e) {
			throw new SerializationException(e);
		} finally {
			try {
				dataIn.close();
			} catch (IOException e) {
				throw new SerializationException(e);
			}
			try {
				byteIn.close();
			} catch (IOException e) {
				throw new SerializationException(e);
			}
		}
	}
}
